/** 
 * Description:商品管理类
 * Date:2011-11-15
 * Author:Along	
*/
package com.community.shopping.web;


import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.text.SimpleDateFormat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.community.shopping.domain.Goods;
import com.community.shopping.domain.GoodsBrand;
import com.community.shopping.domain.GoodsType;
import com.community.shopping.service.logic.GoodsBrandManager;
import com.community.shopping.service.logic.GoodsManager;
import com.community.shopping.service.logic.GoodsTypeManager;
import com.community.shopping.service.logic.Page;
import com.community.shopping.util.FileUpload;
import com.community.shopping.util.FileUtil;
import com.community.shopping.util.FreeMarkerUtil;
import com.community.shopping.util.RequestHelp;

import freemarker.template.Configuration;
import freemarker.template.Template;

@Controller 
public class GoodsControl {
	
	//存放商品信息的目录
	public static final String GOODS_FOLDER="goods";
	//存放商品组图图片的目录
	public static final String GOODS_FOLDER_GROUPIMG="group";
	//存放商品描述图片的目录
	public static final String GOODS_FOLDER_DESCIMG="image";

	@Autowired  
    private GoodsManager goodsManager;
	@Autowired  
    private GoodsTypeManager goodsTypeManager;
	@Autowired  
    private GoodsBrandManager goodsBrandManager;
	private SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	
	/**
	 * 商品列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/goodslist")
	 public ModelAndView list(HttpServletRequest request) 
   { 
    ModelAndView modelAndView = new ModelAndView("goods/goods_list.jsp"); 
    Page page=new Page(request);		
	String searchKey=request.getParameter("searchKey");
	String type=request.getParameter("type");
	String hql=" 1=1 ";
	if(StringUtils.isNotBlank(searchKey))
	{
		hql=hql+" and (goodsName like '%"+searchKey.trim()+"%' or goodsNO like '%"+searchKey+"%' )";
	}
	if(StringUtils.isNotBlank(type))
	{
		hql=hql+" and goodType.typeName  like '%"+type.trim()+"%' ";
	}
	Integer shopId=RequestHelp.getShopId(request);
	List<Goods> goodslist=goodsManager.getGoods(hql+" and shopId="+shopId,page);
	modelAndView.addObject("goodslist", goodslist); 
	modelAndView.addObject("page", page); 
    return modelAndView; 		
	} 
	
	/**
	 * 商品列表
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/goodsselect")
	 public ModelAndView goodsselect(HttpServletRequest request) 
   { 
    ModelAndView modelAndView = new ModelAndView("goods/goods_select.jsp"); 
    Page page=new Page(request,10);		
	String searchKey=request.getParameter("searchKey");
	String type=request.getParameter("type");
	String hql=" 1=1 ";
	if(StringUtils.isNotBlank(searchKey))
	{
		hql=hql+" and (goodsName like '%"+searchKey.trim()+"%' or goodsNO like '%"+searchKey+"%' )";
	}
	if(StringUtils.isNotBlank(type))
	{
		hql=hql+" and goodType.typeName  like '%"+type.trim()+"%' ";
	}
	Integer shopId=RequestHelp.getShopId(request);
	List<Goods> goodslist=goodsManager.getGoods(hql+" and shopId="+shopId,page);
	modelAndView.addObject("goodslist", goodslist); 
	modelAndView.addObject("page", page); 
    return modelAndView; 		
	} 
	
	/**
	 * 添加商品
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/goodsadd")
	 public ModelAndView goodsAdd(HttpServletRequest request) 
    { 
     ModelAndView modelAndView = new ModelAndView("goods/goods_add.jsp"); 
     Integer shopId=RequestHelp.getShopId(request);
     List topTypes=goodsTypeManager.getTopGoodsType(shopId);
     modelAndView.addObject("toptypes", topTypes); 
     return modelAndView; 		

	  } 
	/**
	 * 修改商品
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/goodsedit")
	 public ModelAndView goodsEdit(HttpServletRequest request) 
    { 
     ModelAndView modelAndView = new ModelAndView("goods/goods_edit.jsp"); 
	  String goodsid=request.getParameter("id");
      Goods goods=goodsManager.getGoodsById(Integer.valueOf(goodsid));
	  modelAndView.addObject("goods", goods);
	  
	  String systemBase=request.getSession().getServletContext().getRealPath("/");
	  String folder=systemBase+"data/"+RequestHelp.getShopId(request)+"/"+GOODS_FOLDER+"/"+goods.getUUID();
	  //读取详情信息
	  String editor=FileUtil.readTextFile(folder+"/"+"desc.html", "utf-8");
	  modelAndView.addObject("editor", editor);	  
	  //读取图片信息
	  String[] fileNames=FileUtil.listFile(folder+"/"+GOODS_FOLDER_GROUPIMG);
	  if(fileNames!=null)
	  {
	  for(int i=0;i<fileNames.length;i++)
	  {
		  fileNames[i]=request.getContextPath()+"/data/"+RequestHelp.getShopId(request)+"/"+GOODS_FOLDER+"/"+goods.getUUID()+"/group/"+fileNames[i];		  
	  }
	  }
	  modelAndView.addObject("fileNames", fileNames);	  
	  Integer shopId=RequestHelp.getShopId(request);
	  List topTypes=goodsTypeManager.getTopGoodsType(shopId);
	  modelAndView.addObject("toptypes", topTypes); 
	  modelAndView.addObject("toptypes", topTypes); 
	  List brands=goodsBrandManager.getGoodsBrandByType(goods.getGoodType().getId());
	  modelAndView.addObject("brands", brands); 
	 //修改商品时保存列表页的查询条件，保存后返回时才能保留在原界面  
	  String searchKey=request.getParameter("searchKey");
	  String type=request.getParameter("type");
	  modelAndView.addObject("searchKey", searchKey); 
	  modelAndView.addObject("type", type);
	  modelAndView.addObject("page", new Page(request)); 
      return modelAndView; 		

	  } 
	/**
	 * 保存商品基本信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/goodssave")
	 public ModelAndView save(HttpServletRequest request) throws Exception
    {  	
	 String goodsId=request.getParameter("id");
	 String brandid=request.getParameter("brandid");
	 String typeid=request.getParameter("typeid");
	 Map parameter=request.getParameterMap();
	 Goods goods=new Goods();	
	 //如果是新商品保存，创建存放商品静态页面的目录
	 if(StringUtils.isBlank(goodsId))
	 {	
		 BeanUtils.populate(goods, parameter);
		 Integer shopId=RequestHelp.getShopId(request);
		 goods.setShopId(shopId);
		 goods.setStatus(1);
		 goods.setUUID(UUID.randomUUID().toString().replaceAll("-", ""));
		 goodsManager.save(goods);	
		
	 }else
	 {
		 goods=goodsManager.getGoodsById(Integer.parseInt(goodsId));
		 goods.setIsMarketable(0);
		 goods.setIsBest(0);
		 goods.setIsNew(0);
		 goods.setIsHot(0);
		 BeanUtils.populate(goods, request.getParameterMap());
	 }
	 //单独处理子对象
	 if(StringUtils.isNotBlank(brandid))
	 {	
		 GoodsBrand brand=goodsBrandManager.getGoodsBrand(Integer.parseInt(brandid));
		 goods.setBrand(brand);
	 }else
	 {
		 goods.setBrand(null);
	 }
	 if(StringUtils.isNotBlank(typeid))
	 {	
		 GoodsType type=goodsTypeManager.getGoodsType(Integer.parseInt(typeid));
		 goods.setGoodType(type);
	 }
	//创建保存商品详情的目录
	 String systemBase=request.getSession().getServletContext().getRealPath("/");
	 FileUtil.createPath(systemBase+"data",RequestHelp.getShopId(request)+","+GOODS_FOLDER+","+goods.getUUID()+","+GOODS_FOLDER_GROUPIMG);
	 FileUtil.createPath(systemBase+"data",RequestHelp.getShopId(request)+","+GOODS_FOLDER+","+goods.getUUID()+","+GOODS_FOLDER_DESCIMG);
	 goodsManager.save(goods);	
	 ModelAndView modelAndView = new ModelAndView("goodslist.do");  
     return modelAndView; 		
	  } 
	/**
	 * 保存商品描述信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/goodsdescsave")
	public void saveDesc(HttpServletRequest request,HttpServletResponse response) throws Exception  
	{
		String goodsid=request.getParameter("id");
		Goods goods=goodsManager.getGoodsById(Integer.parseInt(goodsid));
		//保存商品描述
		String goods_desc=request.getParameter("editor"); 		
		String systemBase=request.getSession().getServletContext().getRealPath("/");
		String folder=systemBase+"data/"+RequestHelp.getShopId(request)+"/"+GOODS_FOLDER+"/"+goods.getUUID()+"/";
		FileUtil.checkPath(folder);
		try{//生成新的html详情描述文件		 
		 File descFile=new File(folder+"desc.html");
		 FileWriter writer = new FileWriter(descFile);
         writer.write(goods_desc);
         writer.close();
		 }catch (IOException e){	
			 e.printStackTrace();
			 response.getWriter().print(0); 
		}
		//删除多余的图片
		FileUtil.deleteAllFile(folder+"image",goods_desc);
		response.getWriter().print(1); 		
		
		Configuration cfg =new Configuration();
		cfg.setDefaultEncoding("UTF-8");  
		cfg.setServletContextForTemplateLoading(request.getSession().getServletContext(), "common");
		Map root =new HashMap();
		root.put("name","Tom");
		Template t = cfg.getTemplate("index.ftl");
		t.setEncoding("UTF-8");
		Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(systemBase+"test.html"), "UTF-8"));  
		t.process(root, out);

	}
	/**
	 * 保存商品图片信息
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/goodsimgsave")
	public void saveImage(HttpServletRequest request,HttpServletResponse response) throws Exception  
	{
		String id=request.getParameter("id");
		 Goods goods=goodsManager.getGoodsById(Integer.parseInt(id));
		String systemBase=request.getSession().getServletContext().getRealPath("/");
		String folder=systemBase+"data/"+RequestHelp.getShopId(request)+"/"+GOODS_FOLDER+"/"+goods.getUUID()+"/"+GOODS_FOLDER_GROUPIMG;
		String[] fileNames=FileUtil.listFile(folder);	
		StringBuilder sb=new StringBuilder();
		for(int i=0;i<fileNames.length;i++)
		{
			String fileName=fileNames[i];
			if(i==0)
			{
				sb.append("<div class=bigImg><img src=group/"+fileName+"></div>");
				sb.append("<div class=sImg>");
			}
			sb.append("<img src=group/"+fileName+">");
		}
		sb.append("</div>");
		try{//根据模板生成新的html组图信息	
		 File imgFile=new File(folder+"img.html");
		 FileWriter writer = new FileWriter(imgFile);
         writer.write(sb.toString());
         writer.close();
		 }catch (Exception e){	
			 e.printStackTrace();
			 response.getWriter().print(0); 
		}
		response.getWriter().print(1); 		
	}
	/**
	 * 删除商品
	 * @param request
	 * @return
	 */
	@RequestMapping("/admin/goodsdelete")
	 public void delete(HttpServletRequest request ,HttpServletResponse response)throws Exception
    {  	
	 String[] ids=request.getParameterValues("ids");
	  for(int i=0;i<ids.length;i++)
	  {		
		 Goods goods=goodsManager.getGoodsById(Integer.valueOf(ids[i])); 
		 goods.setIsMarketable(0);
		 goods.setStatus(0);		
		 goodsManager.save(goods);		 
	  }
	 response.setCharacterEncoding("UTF-8");
	 response.getWriter().print("{\"status\":\"success\",\"message\":\"成功删除商品!\"}"); 	

    }
	/**
	 * 商品组图图片上传
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/admin/imgUpload")
	 public void imgUpload(HttpServletRequest request,HttpServletResponse response) throws Exception
    { 
	   String systemBase=request.getSession().getServletContext().getRealPath("/");
	   String goodsId=request.getParameter("goodsid");
	   Goods goods=goodsManager.getGoodsById(Integer.parseInt(goodsId));
	   String folder=systemBase+"/data/"+RequestHelp.getShopId(request)+"/"+GOODS_FOLDER+"/"+goods.getUUID()+"/group/";
		   try{
		   File myPath = new File(folder);
			if (!myPath.exists()) {
				myPath.mkdir();
			}}catch(Exception e){
				e.printStackTrace();
	   }
	   
       String serverFileName=FileUpload.fileUpload(request,"Filedata",folder);
       response.getWriter().print(request.getContextPath()+"/data/"+RequestHelp.getShopId(request)+"/"+GOODS_FOLDER+"/"+goods.getUUID()+"/group/"+serverFileName); 		
	  } 
	
	/**
	 * 删除商品组图图片
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/admin/imgDel")
	 public void imgDel(HttpServletRequest request,HttpServletResponse response) throws Exception
    { 
       String goodsId=request.getParameter("id");
       Goods goods=goodsManager.getGoodsById(Integer.parseInt(goodsId));
	   String imgname=request.getParameter("imgname");
	   String systemBase=request.getSession().getServletContext().getRealPath("/");
	   String folder=systemBase+"/data/"+RequestHelp.getShopId(request)+"/"+GOODS_FOLDER+"/"+goods.getUUID()+"/group/";
	   File imgFile = new File(folder+imgname);
	   imgFile.delete();
	   } 
	/**
	 * 生成商品详细页缓存HTML
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/admin/saveGoodsHtml")
	 public void saveHtml(HttpServletRequest request,HttpServletResponse response) throws Exception
    { 
       String goodsId=request.getParameter("id");
       Goods goods=goodsManager.getGoodsById(Integer.parseInt(goodsId));
       String systemBase=request.getSession().getServletContext().getRealPath("/");
	   String folder=systemBase+"/cache/";
       File test=new File(folder+goods.getUUID()+".html");
       Map root=new HashMap();
  	   root.put("goods", goods);
       FreeMarkerUtil.getInstance(request.getSession().getServletContext()).createHTML("goodsDetail.ftl", root, test);
	   }
	
	/**
	 * 查看商品详情页
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/product/*")
	 public ModelAndView queryProduct(HttpServletRequest request,HttpServletResponse response) throws Exception
    { 		
       String url=request.getRequestURL().toString();
       String htmlName=url.substring(url.lastIndexOf("/")+1);
       String folder=request.getSession().getServletContext().getRealPath("/")+"cache/";
       File test=new File(folder+htmlName+".html");
       if(!test.exists())
       {
    	  
    	   
       }
       ModelAndView modelAndView = new ModelAndView("/cache/"+htmlName+".html");  
  
      // FreeMarkerUtil.getInstance(request.getSession().getServletContext()).createHTML("goodsDetail.ftl", root, test);
	   return modelAndView;
    } 
	
	@RequestMapping("/goods/search")
	public void getGoodsSearch(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		Page page=new Page(request,10);		
		String key=new String(request.getParameter("key").getBytes("iso8859-1"),"UTF-8");
		key=java.net.URLDecoder.decode(key, "UTF-8");  
		List<Goods> goodsList=goodsManager.getGoods(" goodsName like '%"+key+"%' and ifScore='0' ",page);
		StringBuilder sb=new StringBuilder("{\"goods\":[");
		for(Goods goods:goodsList)
		{
			if(sb.length()>20)
			{
				sb.append(",");	
			}
			sb.append("{");
			sb.append("\"id\":\""+goods.getId()+"\",");
			sb.append("\"price\":\""+goods.getPrice()+"\",");
			sb.append("\"oldprice\":\""+goods.getHistoryPrice()+"\",");
			sb.append("\"num\":\""+goods.getGoodsNum()+"\",");
			//sb.append("\"ifdiscount\":\""+goods.getIfDiscount()+"\",");
			sb.append("\"commentscore\":\""+goods.getCommentScore()+"\",");
			//sb.append("\"comments\":\""+goods.getComments()+"\",");
			sb.append("\"goodsname\":\""+goods.getGoodsName()+"\"");
			sb.append("}");		
		}
		sb.append("],\"pageno\":\""+page.getCurrentPage()+"\",\"totalpage\":\""+page.getTotalPages()
				+"\",\"totalsize\":\""+page.getTotalRowsAmount()+"\"}");
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sb.toString()); 			
	}

	//将cookie保存到session中
	@RequestMapping("/goodscookie/set")
	public void setGoodsCookie(HttpServletRequest request,HttpServletResponse response)throws Exception
	{
		String cookie=request.getParameter("cookie");
		request.getSession().setAttribute("cookie", cookie);
	}
	
	
	
	/**
	 * 条码扫描
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/goods/scan")
	public void queryGoodsByScan(HttpServletRequest request,HttpServletResponse response)throws Exception
	{	
		String scan=request.getParameter("scan");
		List<Goods> goodsList=goodsManager.getGoods(" ifScore=0 and ifDiscount=0 and goodsNO='"+scan+"' ");
		StringBuilder sb=new StringBuilder("");
		if(goodsList.size()>0)
		{
		Goods goods=goodsList.get(0);		
		    sb.append("{");
			sb.append("\"id\":\""+goods.getId()+"\",");
			sb.append("\"price\":\""+goods.getPrice()+"\",");
			sb.append("\"goodsname\":\""+goods.getGoodsName()+"\"");
			sb.append("}");		
		
		response.setCharacterEncoding("UTF-8");
		response.getWriter().print(sb.toString()); 			 			
	 }
	}
	
	/**
	 * 条码扫描，减库存
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	@RequestMapping("/goods/scandel")
	public void deletenum(HttpServletRequest request,HttpServletResponse response)throws Exception
	{	
	  String goodsinfos=request.getParameter("goodsinfos");
	  String [] goodsdetails=goodsinfos.split(",");
	  for(int i=0;i<goodsdetails.length;i++)
	  {
		  String goodsdetail=goodsdetails[i];
		  String[] infos=goodsdetail.split("_");
		  String goodsid=infos[0];
		  String goodsnum=infos[1];
		  Goods goods=goodsManager.getGoodsById(Integer.parseInt(goodsid));
		  if(goods.getGoodsNum()>Integer.parseInt(goodsnum))
		  {
		  goods.setGoodsNum(goods.getGoodsNum()-Integer.parseInt(goodsnum));
		  }
		  else
		  {
			  goods.setGoodsNum(0);  			  
		  }
		  goods.setSaleNum(goods.getSaleNum()+Integer.parseInt(goodsnum));
		  goodsManager.save(goods);
	  }
		
		
	}
   

}
